package com.soft.base.mybatis.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.soft.base.mybatis.type.ListString;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
@MappedTypes({ListString.class})
public class ListStringTypeHandler implements TypeHandler<ListString> {
    @Override
    public void setParameter(PreparedStatement ps, int i, ListString parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            ps.setString(i, null);
            return;
        }
        String json = JSON.toJSONString(parameter);
        ps.setString(i, json);
    }

    @Override
    public ListString getResult(ResultSet rs, String columnName) throws SQLException {
        ListString ret = JSONArray.parseObject(rs.getString(columnName), ListString.class);
        if (null == ret) {
            ret = new ListString();
        }
        return ret;
    }

    @Override
    public ListString getResult(ResultSet rs, int columnIndex) throws SQLException {
        ListString ret = JSONArray.parseObject(rs.getString(columnIndex), ListString.class);
        if (null == ret) {
            ret = new ListString();
        }
        return ret;
    }

    @Override
    public ListString getResult(CallableStatement cs, int columnIndex) throws SQLException {
        ListString ret = JSONArray.parseObject(cs.getString(columnIndex), ListString.class);
        if (null == ret) {
            ret = new ListString();
        }
        return ret;
    }
}
